package service

import (
	"fmt"
	"choujiang/common/db"
	"choujiang/common/models"
	"choujiang/common/utils"
	"strconv"
)

type Groups struct {
	NickName   string `json:"nick_name"`
	HeadImgUrl string `json:"head_img_url"`
	CreatedAt  string `json:"created_at"`
	GroupPoint int64  `json:"group_point"`
}

func GetGroupList(userId, pageNo, pageSize int64) ([]Groups, error) {
	groups := make([]Groups, 0)
	curPageNo := (pageNo - 1) * pageSize
	err := db.MysqlEngine.SQL("select u.nick_name, u.head_img_url, FROM_UNIXTIME(u.created_at) as created_at, ue.group_point from user as u inner join user_extra as ue on u.id = ue.user_id where ue.parent_id = ? order by u.created_at desc limit ?,?", userId, curPageNo, pageSize).Find(&groups)
	if err != nil {
		fmt.Printf("GetGroupList err:%+v\n", err)
	}
	if len(groups) > 0 {
		for i := 0; i < len(groups); i++ {
			groups[i].NickName = utils.DecodeNickName(groups[i].NickName)
		}
	}
	return groups, nil
}

func GetGroupsNum(userId int64) (int64, int64) {
	var todayNum, totalNum int64
	todayAddtionKey := ADDITION_NUM_EVERY_DAY + strconv.FormatInt(userId, 10) + "_" + utils.TodayUnix()
	keyExist := db.MainRedisClient.Exists(todayAddtionKey)
	if keyExist.Val() == 1 {
		reGet := db.MainRedisClient.Get(todayAddtionKey)
		todayNum, _ = strconv.ParseInt(reGet.Val(), 10, 64)
	}
	totalAddtionKey := ADDITION_NUM_TOTAL + strconv.FormatInt(userId, 10)
	totalKeyExist := db.MainRedisClient.Exists(totalAddtionKey)
	if totalKeyExist.Val() == 1 { //key存在
		reVal := db.MainRedisClient.Get(totalAddtionKey)
		totalNum, _ = strconv.ParseInt(reVal.Val(), 10, 64)
	} else {
		userCount, _ := db.MysqlEngine.SQL("select count(*) from user_extra where parent_id = ?", userId).Count()
		db.MainRedisClient.Set(totalAddtionKey, userCount, 0)
		totalNum = userCount
	}

	return todayNum, totalNum
}

func GetMyFriends(userId int64) ([]Groups, int64) {
	groups := make([]Groups, 0)
	err := db.MysqlEngine.SQL("select u.nick_name, u.head_img_url, FROM_UNIXTIME(u.created_at) as created_at, ue.group_point from user as u inner join user_extra as ue on u.id = ue.user_id where ue.parent_id = ? limit ?", userId, 10).Find(&groups)
	if err != nil {
		fmt.Printf("GetGroupList err:%+v\n", err)
	}
	userExtra := new(model.UserExtra)
	total, err := db.MysqlEngine.Where("parent_id=?", userId).Count(userExtra)
	return groups, total
}
